#! /bin/bash

KubectlGet(){
    case $1 in
        svc|SVC|Svc)        sudo kubectl get svc --namespace=$app_prj-$app_env          ;;
        Pod|pod|pods|Pods)  sudo kubectl get pods -o wide --namespace=$app_prj-$app_env ;;
        ClusterIP)          KubectlGet SVC | awk '{print $3}'                           ;;
    esac
}

KubectlPSCD(){
    test -z "$KUBE_YAML_DIR" && KUBE_YAML_DIR=kube_config
    test -d "$KUBE_YAML_DIR" || msg e "Require yaml files location"

    cd $KUBE_YAML_DIR

     yaml_rc="ReplicationController.yaml"
    yaml_svc="Service.yaml"
    
    check file $yaml_rc
    check file $yaml_svc

    prj_name="$app_prj-$APP_SUB"
    svc_name="$prj_name-$app_env"
    
    sed -i "s/$prj_name.*/$svc_name/g" *.yaml

    msg i "Check service $svc_name"
    KubectlGet SVC | grep -q "$svc_name"

    if [ $? = 0 ]
    then
        msg i "Service $svc_name already exist"
    else
        msg i "Create $svc_name"
        sudo kubectl create -f $yaml_svc
    fi

    msg i "Check pod $svc_name"
    KubectlGet Pods | grep -q "$svc_name"

    if [ $? = 0 ]
    then
        msg i "Remove pod $svc_name"
        sudo kubectl delete -f $yaml_rc
    fi
    
    msg i "Create pod $svc_name"
    sudo kubectl create -f $yaml_rc
}
